package pl.controller;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.theme.SessionThemeResolver;

@Controller
public class ThemeManagerController {

	protected final Log log = LogFactory.getLog(getClass());
	
	protected SessionThemeResolver themeResolver;
	
	@RequestMapping("/changeTheme.htm") 
	public ModelMap changeTheme(@RequestParam String theme, HttpServletRequest request, HttpServletResponse response) throws IOException{
		
		try {
			log.debug("changeTheme " + theme);
			
			log.debug(themeResolver);
			
			log.debug("r: " + themeResolver.getDefaultThemeName());
			
			log.debug("rq: " + request);
			
			log.debug("resp " + response);
			
			themeResolver.setThemeName(request, response, theme);
			
			Enumeration<String> e = request.getSession().getAttributeNames();
			
			while (e.hasMoreElements()){
				String prop = e.nextElement();
				log.debug(prop + " " + request.getSession().getAttribute(prop));
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		response.setContentType("text/javascript");
		response.getWriter().append("window.location.reload()").flush();
		
		return  null;
		
	}
	

	public void setThemeResolver(SessionThemeResolver themeResolver) {
		this.themeResolver = themeResolver;
	}

}
